// pages/main/app-center/app-center.js
Page({
  data: {
    searchKeyword: '',
    selectedFilters: [],
    filters: [],
    appList: [],
    filteredAppList: [],
    loading: true,
    appId: null, // 添加应用ID存储
    categoryId: null, // 类别ID
    subCategoryId: null // 子类别ID
  },

  onLoad(options) {
    console.log('id', options.id)
    const appName = options.name ? decodeURIComponent(options.name) : '应用中心';
    
    // 动态设置导航栏标题为应用名称或子类别名称
    const displayName = options.subCategoryName 
      ? decodeURIComponent(options.subCategoryName) 
      : appName;
    
    wx.setNavigationBarTitle({
      title: displayName
    });
    
    this.setData({
      appId: options.appId || options.id || null,
      categoryId: options.categoryId || null,
      subCategoryId: options.subCategoryId || null
    });
    this.loadFilters();
    this.loadAppList();
  },

  // 加载筛选条件
  loadFilters() {
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetAppFilters/`,
      method: 'POST',
      data: {
        app_id: this.data.appId
      },
      success: (res) => {
        if (res.data.status) {
          const filters = res.data.filters || [];
          // 为每个选项添加selected属性
          filters.forEach(filter => {
            filter.options.forEach(option => {
              option.selected = false;
            });
          });
          this.setData({
            filters: filters
          });
        }
      },
      fail: (err) => {
        console.error('获取筛选条件失败:', err);
      }
    });
  },

  // 加载应用列表
  loadAppList() {
    this.setData({ loading: true });
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetAppCenterList/`,
      method: 'POST',
      data: {
        search: this.data.searchKeyword,
        filters: this.data.selectedFilters,
        app_id: this.data.appId
      },
      success: (res) => {
        if (res.data.status) {
          const appList = res.data.apps || [];
          this.setData({
            appList: appList,
            filteredAppList: appList,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取应用列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('获取应用列表失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 搜索输入变化（Lin UI 的 linchange 事件）
  onSearchChange(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    // 实时搜索
    this.filterAppList();
  },

  // 搜索确认（Lin UI 的 linconfirm 事件 - 点击键盘完成按钮）
  onSearchConfirm(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterAppList();
    console.log('搜索确认:', keyword);
  },

  // 清除搜索（Lin UI 的 linclear 事件）
  onSearchClear() {
    this.setData({ 
      searchKeyword: '',
      filteredAppList: this.data.appList
    });
    console.log('清除搜索');
  },

  // 取消搜索（Lin UI 的 lincancel 事件）
  onSearchCancel() {
    this.setData({ 
      searchKeyword: '',
      filteredAppList: this.data.appList
    });
    console.log('取消搜索');
  },

  // 筛选条件点击
  onFilterTap(e) {
    const filterId = e.currentTarget.dataset.filterId;
    const filterValue = e.currentTarget.dataset.filterValue;
    let selectedFilters = [...this.data.selectedFilters];
    let filters = [...this.data.filters];
    
    const existingIndex = selectedFilters.findIndex(f => f.id === filterId);
    let isRemoving = false;
    
    if (existingIndex > -1) {
      // 如果已选中相同筛选项，则移除
      if (selectedFilters[existingIndex].value === filterValue) {
        selectedFilters.splice(existingIndex, 1);
        isRemoving = true;
      } else {
        // 替换为新的筛选值
        selectedFilters[existingIndex].value = filterValue;
      }
    } else {
      // 添加新的筛选项
      selectedFilters.push({ id: filterId, value: filterValue });
    }
    
    // 更新UI状态
    filters.forEach(filter => {
      if (filter.id === filterId) {
        filter.options.forEach(option => {
          if (option.value === filterValue) {
            option.selected = !isRemoving;
          } else {
            option.selected = false; // 同一类型的其他选项取消选中
          }
        });
      }
    });
    
    this.setData({ 
      selectedFilters,
      filters
    });
    this.filterAppList();
  },

  // 筛选应用列表
  filterAppList() {
    let filteredList = [...this.data.appList];
    
    // 搜索筛选
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase();
      console.log('搜索关键词：', keyword);
      filteredList = filteredList.filter(app => {
        const name = (app.name || '').toLowerCase();
        const description = (app.description || '').toLowerCase();
        const category = (app.category || '').toLowerCase();
        return name.includes(keyword) || 
               description.includes(keyword) || 
               category.includes(keyword);
      });
    }
    
    // 条件筛选
    if (this.data.selectedFilters.length > 0) {
      filteredList = filteredList.filter(app => {
        return this.data.selectedFilters.every(filter => {
          switch(filter.id) {
            case 'category':
              return (app.category || '') === filter.value;
            case 'status':
              return (app.status || '') === filter.value;
            case 'priority':
              return (app.priority || '') === filter.value;
            default:
              return true;
          }
        });
      });
    }
    
    this.setData({ filteredAppList: filteredList });
  },

  // 应用项点击（现在点击的是项目）
  onAppTap(e) {
    const app = e.currentTarget.dataset.app;
    let url = `/pages/main/app-detail/app-detail?id=${app.id}&context_id=${this.data.appId || ''}`;
    
    // 如果有类别信息，添加到URL参数中
    if (this.data.categoryId) {
      url += `&category_id=${this.data.categoryId}`;
    }
    if (this.data.subCategoryId) {
      url += `&sub_category_id=${this.data.subCategoryId}`;
    }
    
    wx.navigateTo({
      url: url
    });
  },

  // 清除所有筛选
  onClearFilters() {
    let filters = [...this.data.filters];
    // 重置所有选项的选中状态
    filters.forEach(filter => {
      filter.options.forEach(option => {
        option.selected = false;
      });
    });
    
    this.setData({
      searchKeyword: '',
      selectedFilters: [],
      filters: filters,
      filteredAppList: this.data.appList
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadAppList();
    wx.stopPullDownRefresh();
  }
});
